package cn.flkj.lucia1a4a1.intermediate;

import org.apache.commons.io.IOUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.hyperledger.fabric.sdk.User;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.Security;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : 州长在手 2021/1/14 上午8:56
 */
public class FabricStore implements IntermediateFabricStore {


    private static class FabricStoreMapHolder {
        private static final FabricStore fs = new FabricStore();
    }
    public static FabricStore getInstance() {
        return FabricStoreMapHolder.fs;
    }

    static {
        try {
            Security.addProvider(new BouncyCastleProvider());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 用户信息集合
    private final Map<String, IntermediateUser> members = new HashMap<>();

    public FabricStore() {}

    @Override
    public void saveState(String keyForFabricStoreName,User user) {
        members.put(keyForFabricStoreName,(IntermediateUser) user);
    }

    @Override
    public IntermediateUser getState(String keyValStoreName) {
        return members.get(keyValStoreName);
    }

    @Override
    public void saveMember( IntermediateUser user) throws IOException {
        String certificate = new String(IOUtils.toByteArray(new FileInputStream(new File(user.getCertificatePath()))), "UTF-8");
        String skString = new String(IOUtils.toByteArray(new FileInputStream(new File(user.getSkPath()))), "UTF-8");
        PrivateKey privateKey = Utils.getPrivateKeyFromBytes(skString);
        user.setEnrollment(new IntermediateEnrollment(privateKey, certificate));
        members.put(user.getKeyForFabricStoreName(), user);
    }

    @Override
    public IntermediateUser getMember(String leagueName, String orgName, String peerName, String name, String mspId, String skPath, String certificatePath) throws IOException {
        String keyValStoreName = IntermediateUser.toKeyValStoreName(leagueName, orgName, peerName, name);
        // 尝试从缓存中获取User状态
        IntermediateUser user = members.get(keyValStoreName);
        if (null != user) {
            return user;
        }
        // 创建User，并尝试从键值存储中恢复它的状态(如果找到的话)
        user = new IntermediateUser(leagueName, orgName, peerName, name, skPath, certificatePath,mspId);
        String certificate = new String(IOUtils.toByteArray(new FileInputStream(new File(certificatePath))), "UTF-8");
        String skString = new String(IOUtils.toByteArray(new FileInputStream(new File(skPath))), "UTF-8");
        PrivateKey privateKey = Utils.getPrivateKeyFromBytes(skString);
        user.setEnrollment(new IntermediateEnrollment(privateKey, certificate));
        // 执行更新FS
        members.put(keyValStoreName, user);
        return user;
    }

}
